package keter.framework.web.util;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestUtil {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);
    
    /**
     * 从
     * 注意每个request只能使用一次。
     * @param 
     * @return 
     * @author  gulixing@msn.com
     * @date    2015年11月27日
     */
    public  static String getJson(HttpServletRequest request) {
        if(!StringUtils.contains(request.getHeader("Content-Type"), "application/json")){
            throw new RuntimeException("API使用错误：只对Content-Type为application/json的请求进行处理！");
        }
        StringBuffer json = new StringBuffer();
        String line = null;
        BufferedReader reader;
        try {
            reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
        } catch (IOException e) {
            logger.error("json读取失败", e);
        }
        return json.toString();
    }
    
	public static boolean isAjax(HttpServletRequest request) {
	    if(StringUtils.isNotEmpty(request.getHeader("accept"))){
		return request.getHeader("accept").contains("application/json") || 
		        (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest"));
	    }
	    return false;
	}

}
